1.Se citeste de la tastatura un numar natural n par, n<30. Sa se genereze si sa se afiseze pe ecran toate combinatiile de n paranteze rotunde care se închid corect. De exemplu, pentru n=4 se obtin urmatoarele combinatii: ( ( ) ) si ( ) ( ) .
#include<iostream> using namespace std;
int s[10],n;
void init(int k){ s[k]=-1; }
int succesor(int k) { if(s[k]<1) {s[k]=s[k]+1; return 1;} else return 0;}
int valid(int k){ int i,pi=0,pd=0; for(i=1;i<=k;i++) if(s[i]==0) pd++; else pi++; return pd<=n/2 && pi<=pd;}
int solutie(int k){ return k==n;} void tipar() { int j; cout<<endl; for(j=1;j<=n;j++) if(s[j]==1) cout<<")"; else cout<<"("; }
void bt(int k){
init(k);
while(succesor(k))
if(valid(k)) if(solutie(k)) tipar();
else bt(k+1);}
main()
{
cin>>n;
bt(1);
}
2.Sa se aranjeze in toate modurile n pisici si m caini astfel incat nicio pisica sa nu fie asezata intre 2 caini.
#include<iostream>
using namespace std;
int x[100],n,m,nr=0;
void init(int k){
#include<iostream>
using namespace std;
int s[10],n;
void init(int k){
s[k]=-1;
}
int succesor(int k)
{
if(s[k]<1)
{s[k]=s[k]+1; return 1;}
else return 0;}
int valid(int k){
int i,pi=0,pd=0;
for(i=1;i<=k;i++)
if(s[i]==0) pd++;
else pi++;
return pd<=n/2 && pi<=pd;}
int solutie(int k){
return k==n;}
void tipar()
{ int j;
cout<<endl;
for(j=1;j<=n;j++)
if(s[j]==1) cout<<")";
else cout<<"(";
}
void bt(int k){
init(k);
while(succesor(k))
if(valid(k)) if(solutie(k)) tipar();
else bt(k+1);}
main()
{
cin>>n;
bt(1);
}
2.Sa se aranjeze in toate modurile n pisici si m caini astfel incat nicio pisica sa nu fie asezata intre 2 caini.
#include<iostream>
using namespace std;
int x[100],n,m,nr=0;
void init(int k){
x[k]=-1;
}
int succesor(int k)
{
if(x[k]<1)
{x[k]=x[k]+1; return 1;}
else return 0;}
int valid(int k){
int c=0,p=0,i;
for(i=1;i<=k;i++)
if(x[i]==0) c++;
else p++;
if(p>n || c>m) return 0;
if(k>=3) if(x[k-2]==0 && x[k-1]==1 && x[k]==0) return 0;
return 1;
}
int solutie(int k){
return k==n+m;}
void tipar()
{ for(int i=1;i<=n+m;i++) if(x[i]==1) cout<<"P ";
else cout<<"C ";
cout<<endl;
nr++;
}
void bt(int k){
init(k);
while(succesor(k))
if(valid(k)) if(solutie(k)) tipar();
else bt(k+1);}
int main()
{ cin>>n>>m;
bt(1);
cout<<nr;
return 0;
}